package com.jusyl.cristo.auth.action;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jusyl.cristo.auth.busi.AuthBusi;
import com.jusyl.cristo.auth.model.AuthRole;
import com.jusyl.cristo.auth.model.AuthUser;

import lombok.extern.slf4j.Slf4j;

@Controller
public class AuthAction {
	Logger logger = LoggerFactory.getLogger(AuthAction.class);
	@Autowired
	AuthBusi ab;

	
	/**
	 * 专为使用ftl的首页使用
	 * @return
	 */
	@RequestMapping("index")
	public String index() {
		return "index";
	}
	
	@RequestMapping("auth/authManagement")
	public String authManagement() {
		return "/back/AuthManagement";
	}
	
	@RequestMapping(value="back/login", method=RequestMethod.POST)
	public String authLogin(@ModelAttribute("username") String username, @ModelAttribute("password") String password) {
		logger.info("进入登陆, UN" + username+password);
		ab.login(StringUtils.trim(username), StringUtils.trim(password));
		
		return "/back/index";
	}
	
	
	@RequestMapping(value="auth/getUsers", method=RequestMethod.GET)
	public String getUsers(Model model) {
		
		List<AuthUser> list1 = ab.getUsers();
		model.addAttribute("users", list1);
		List<AuthRole> list2 = ab.getRoles();
		model.addAttribute("roles", list2);
		
		return "/back/userList";
	}
	
	@RequestMapping("/auth/addUser")
	public String authAddUser(String name, String password, Model model) {
		int result = ab.addUser(name, password);
		
		List<AuthUser> list1 = ab.getUsers();
		model.addAttribute("users", list1);
		List<AuthRole> list2 = ab.getRoles();
		model.addAttribute("roles", list2);
		
		return "/back/userList";
	}
	
	
	
	@RequestMapping(value="auth/getRoles", method=RequestMethod.GET)
	public String getRoles(Model model) {
		
		List<AuthUser> list1 = ab.getUsers();
		model.addAttribute("users", list1);
		List<AuthRole> list2 = ab.getRoles();
		model.addAttribute("roles", list2);
		
		return "/back/userList";
	}
	
	@RequestMapping("/auth/addRole")
	public String authAddRole(String roleName, Model model) {
		int result = ab.addRole(roleName);
		List<AuthUser> list1 = ab.getUsers();
		model.addAttribute("users", list1);
		List<AuthRole> list2 = ab.getRoles();
		model.addAttribute("roles", list2);
		return "/back/userList";
	}
}
